package com.ruoyi.chat.service.impl;

import com.ruoyi.chat.domain.ChatDataset;
import com.ruoyi.chat.mapper.ChatDatasetMapper;
import com.ruoyi.chat.service.IChatDatasetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 助手知识库关联Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-27
 */
@Service
public class ChatDatasetServiceImpl implements IChatDatasetService
{
    @Autowired
    private ChatDatasetMapper chatDatasetMapper;

    /**
     * 查询助手知识库关联
     * 
     * @param chatId 助手知识库关联主键
     * @return 助手知识库关联
     */
    @Override
    public ChatDataset selectChatDatasetByChatId(Long chatId)
    {
        return chatDatasetMapper.selectChatDatasetByChatId(chatId);
    }

    /**
     * 查询助手知识库关联列表
     * 
     * @param chatDataset 助手知识库关联
     * @return 助手知识库关联
     */
    @Override
    public List<ChatDataset> selectChatDatasetList(ChatDataset chatDataset)
    {
        return chatDatasetMapper.selectChatDatasetList(chatDataset);
    }

    /**
     * 新增助手知识库关联
     * 
     * @param chatDataset 助手知识库关联
     * @return 结果
     */
    @Override
    public int insertChatDataset(ChatDataset chatDataset)
    {
        return chatDatasetMapper.insertChatDataset(chatDataset);
    }

    /**
     * 修改助手知识库关联
     * 
     * @param chatDataset 助手知识库关联
     * @return 结果
     */
    @Override
    public int updateChatDataset(ChatDataset chatDataset)
    {
        return chatDatasetMapper.updateChatDataset(chatDataset);
    }

    /**
     * 批量删除助手知识库关联
     * 
     * @param chatIds 需要删除的助手知识库关联主键
     * @return 结果
     */
    @Override
    public int deleteChatDatasetByChatIds(Long[] chatIds)
    {
        return chatDatasetMapper.deleteChatDatasetByChatIds(chatIds);
    }

    /**
     * 删除助手知识库关联信息
     * 
     * @param chatId 助手知识库关联主键
     * @return 结果
     */
    @Override
    public int deleteChatDatasetByChatId(Long chatId)
    {
        return chatDatasetMapper.deleteChatDatasetByChatId(chatId);
    }

    @Override
    public void chatDatasetRelate(Long chatId, List<Long> datasetIds) {
        // 先清空知识库之前绑定的角色
        chatDatasetMapper.deleteChatDatasetByChatId(chatId);
        // 重新绑定
        // 如果新绑定的知识库ids为空 则直接返回
        if (CollectionUtils.isEmpty(datasetIds)) {
            return;
        }
        List<ChatDataset> chatDatasets = new ArrayList<>();
        datasetIds.forEach(datasetId -> {
            chatDatasets.add(new ChatDataset(chatId, datasetId));
        });
        chatDatasetMapper.batchAddChatDataset(chatDatasets);
    }
}
